package helper

import (
    "errors"
    "fmt"
    "server/app"
    "strings"
)

// 查询数据库对象分页列表
func FindPageList(list interface{}, pageIndex int, pageSize int, table string, cols string,
    condition string, orderby string, args ...interface{}) (pageList *app.PageListResult, err error) {
    if len(orderby) == 0 {
        return nil, errors.New("请指定排序语句")
    }
    if pageIndex <= 0 {
        pageIndex = 1
    }
    if pageSize <= 0 {
        pageSize = 10
    }
    db := app.GetDatabase()

    sqlStr := BuildPageSQL(table, cols, condition, orderby)
    startIndex := (pageIndex-1)*pageSize + 1
    endIndex := startIndex + pageSize - 1
    args = append(args, startIndex, endIndex)
    PrintLogSQL(sqlStr, args...)

    err = db.Select(list, sqlStr, args...)
    if err != nil {
        return
    }
    pageList = new(app.PageListResult)
    pageList.PageIndex = pageIndex
    pageList.PageSize = pageSize
    pageList.Rows = list

    countStr := fmt.Sprintf("select count(1) from %s %s", table, condition)
    args = args[0 : len(args)-2]
    err = db.Get(&pageList.Total, countStr, args...)
    PrintLogSQL(countStr, args...)
    return
}

//生成数据库分页SQL语句
//table:表名  cols:列字符串 condition:条件 orderby:排序语句
func BuildPageSQL(table string, cols string, condition string, orderby string) string {
    psql := fmt.Sprintf(`select %s from ( select %s,row_number() over ( %s ) rnum from %s  %s ) _ where rnum between ? and ?`, cols, cols, orderby, table, condition)
    return psql
}

//生成排序SQL语句
func BuildOrderBySQL(sortParams ...app.SortParam) string {
    if len(sortParams) == 0 {
        return app.Empty
    }
    orderby := app.Empty
    for i, item := range sortParams {
        if len(item.SortName) == 0 {
            panic(errors.New("请指定排序字段"))
        }
        if len(item.SortDir) == 0 {
            item.SortDir = "asc"
        }
        orderby += fmt.Sprintf("%s %s", item.SortName, item.SortDir)
        if i > 0 {
            orderby += ","
        }
    }
    if len(orderby) > 0 {
        return "order by " + orderby
    }
    return app.Empty
}

//输出sql日志
func PrintLogSQL(sqlStr string, args ...interface{}) {
    sqlStr = strings.ReplaceAll(sqlStr, "\n", app.Empty)
    sqlStr = strings.ReplaceAll(sqlStr, "?", "%v")
    app.GetLogger().Infof(sqlStr, args...)
}
